let DEBUG = true;

const utilLog = (str) => {
	if (DEBUG) {
		console.log(str);
	}
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 获取设备唯一编码
const getUniqueCode = () => {
	let uniqueCode = ""
	
	try {
		uniqueCode = uni.getStorageSync('uniqueCode')
	} catch (e) {}
	utilLog("设备唯一标识：" + uniqueCode)
	
	if (uniqueCode === "" || uniqueCode === undefined) { //判断是否有唯一标识
		// #ifdef  APP-PLUS
		uniqueCode = plus.device.model + plus.device.uuid
		utilLog(plus.device)
		utilLog(uniqueCode)

		try {
			if (uniqueCode) {
				uni.setStorageSync('uniqueCode', uniqueCode)
			}
		} catch (e) {}
		// #endif
	}
	
	return uniqueCode
}

/**
 * 页面跳转接口
 */
function safetySwitchPage(url) {
  if (!url) {
    return;
  }

  var pages = getCurrentPages();
  //首先查询要跳转的页面是否存在
  var pageIndex = -1;
  for (var i = 0; i < pages.length; ++i) {
    //查询这个页面是否存在
    var index = url.indexOf(pages[i].route);
    if (index > -1) {
      pageIndex = i;
      break;
    }
  }

  //要跳转的页面存在，则直接返回到对应的接口
  if (pageIndex > 0) {
    var prePage = pages[pageIndex];
    var preData = splitUrlString(url);
    if (prePage.setPageData) {
      prePage.setPageData(preData);
    }
    var delta = pages.length - 1 - pageIndex;
    wx.navigateBack({
      delta: delta,
    })
  } else {
    wx.navigateTo({
      url: url,
    })
  }
}

/**
 * 拆分url参数 
 */
function splitUrlString(url) {
  try {
    var data = {};
    var str = url.split("?")[1];
    var items = str.split("&");
    for (var i = 0; i < items.length; ++i) {
      var param = items[i].split("=");
      data[param[0]] = param[1];
    }
    return data;
  } catch (e) {
    return null;
  }
}

module.exports = {
	log: utilLog,
	getUniqueCode,
	splitUrlString,
	formatNumber
}
